package com.hsogoo.collate.configuration;

import com.google.common.collect.Maps;
import com.hsogoo.collate.datasource.DynamicDataSource;
import com.hsogoo.collate.datasource.DynamicDataSourceContextHolder;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.Map;

/**
 * @Author huangsaigang
 * Created @2018/11/23.
 */
@Configuration
public class DataSourceConfig {

    @Value("${collate.driveName}")
    private String driveName;
    @Value("${collate.url}")
    private String url;
    @Value("${collate.username}")
    private String username;
    @Value("${collate.password}")
    private String password;

    @Bean
    @Primary
    public DataSource dynamicDataSource() {
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        DataSource defaultDataSource = createDefaultDataSource();
        dynamicDataSource.setDefaultDataSource(defaultDataSource);
        Map<String ,DataSource> dataSources = Maps.newHashMap();
        dataSources.put(DynamicDataSourceContextHolder.DEFAULT_DATASOURCE, defaultDataSource);
        dynamicDataSource.setDataSources(dataSources);
        return dynamicDataSource;
    }

    private DataSource createDefaultDataSource() {
        HikariConfig config = new HikariConfig();
        config.setDriverClassName(driveName);
        config.setJdbcUrl(url); //数据源
        config.setUsername(username); //用户名
        config.setPassword(password); //密码
        //以下也可以做为配置项,这里为了简化写死了
        config.addDataSourceProperty("cachePrepStmts", "true"); //是否自定义配置，为true时下面两个参数才生效
        config.addDataSourceProperty("prepStmtCacheSize", "250"); //连接池大小默认25，官方推荐250-500
        config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); //单条语句最大长度默认256，官方推荐2048
        config.addDataSourceProperty("useServerPrepStmts", "true"); //新版本MySQL支持服务器端准备，开启能够得到显著性能提升
        config.addDataSourceProperty("useLocalSessionState", "true");
        config.addDataSourceProperty("useLocalTransactionState", "true");
        config.addDataSourceProperty("rewriteBatchedStatements", "true");
        config.addDataSourceProperty("cacheResultSetMetadata", "true");
        config.addDataSourceProperty("cacheServerConfiguration", "true");
        config.addDataSourceProperty("elideSetAutoCommits", "true");
        config.addDataSourceProperty("maintainTimeStats", "false");

        return new HikariDataSource(config);
    }

}
